# -*- coding:utf-8 -*-
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from .models import User
import re
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_verify_email


class UserCreatSerializer(serializers.Serializer):
    # 用户编号,只输出
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(min_length=5,max_length=20,error_messages={
        'min_length':'不少于5个字符',
        'max_length':'不大于20个字符',
    })

    def validated_username(self,value):
        count = User.objects.filter(username=value).count()
        if count>0:
            raise serializers.ValidationError('用户名存在')
        return value

    mobile = serializers.CharField()
    def validate_mobile(self,value):

        if not re.match('',value):
            raise serializers.ValidationError('手机号错误')
        count = User.objects.filter(mobile=value).count()
        if count>0:
            raise serializers.ValidationError('手机号存在')
        return value

    password = serializers.CharField(
        write_only=True,
        min_length=8,max_length=20,
        error_messages={
            'min_length':'长度不能小于8',
            'max_length':'长度不能大于20'
        }
    )
    password2 = serializers.CharField(        write_only=True,
        min_length=8,max_length=20,
        error_messages={
            'min_length':'长度不能小于8',
            'max_length':'长度不能大于20'
        }
    )

    sms_code = serializers.CharField(write_only=True)
    def validate_sms_code(self,value):
        if not re.match(r'^\d{6}$',value):
            raise serializers.ValidationError('验证码格式错误')

        return value

    # 是否同意协议
    allow = serializers.CharField(write_only=True)
    def validate_allow(self,value):
        if not value:
            raise serializers.ValidationError('请同意协议')
        return value






    def validator(self,attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')
        redis_cli = get_redis_connection('verify_code')
        key = 'sms_code_'+attrs.get('mobile')
        sms_code_redis = redis_cli.get(key)
        sms_code_request = attrs.get('sms_code')
        if not sms_code_redis:
            raise serializers.ValidationError('验证码已过期')
        redis_cli.delete(key) # 强制失效
        if sms_code_redis.decode() != sms_code_request: # 从redis取出的数据是二进制,需要转换成字符串
            raise serializers.ValidationError('短信验证码错误')
        return attrs

    # 增加token字段
    token = serializers.CharField(label='登录状态token', read_only=True)


    def create(self, validated_data):
        user=User()
        user.username = validated_data.get('username')
        user.mobile = validated_data.get('mobile')
        user.set_password(validated_data.get('password'))

        user.save()
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')

class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()
        # 生成验证链接
        verify_url = instance.generate_verify_email_url()
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)

        return instance



